<template>
  <c-with-dialog
    ref="cWithDialog"
    v-model="selections"
    multiple
    width="800px"
    method="POST"
    :filters-raw="filtersRaw"
    :params-raw="paramsRaw"
    :columns="columns"
    url="/api/v1/shopDecoration/pageUnitPupSelect"
    :open-fun="openFun"
    title="委派施工单位"
    :search-merge-params-raw="false"
    @open="openHandle"
    @closed="closedHandle"
  >
    <template #btn>
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="confirmHandle">确认</c-button>
    </template>
    <template #header>
      <div>
        <div class="qup-title-box"><span class="border" /><span>申请人信息</span></div>
        <div class="qup-title-box"><span class="border" /><span>门店信息</span></div>
        <div class="qup-title-box"><span class="border" /><span>门店建设信息</span></div>
        <div class="qup-title-box"><span class="border" /><span>装修信息</span></div>
        <div class="qup-title-box"><span class="border" /><span>委派信息</span></div>
        <!-- <div class="qup-title-box"><span class="border" /><span>已选择的施工单位</span></div> -->
      </div>
      <c-list :column="2">
        <c-list-item label="经销商姓名" :value="detail.customerName" />
        <c-list-item label="经销商电话" :value="detail.customerPhone" />
      </c-list>
    </template>
  </c-with-dialog>

</template>
<script>
import { getDetailBatch, postBatchCreateUnit, getGetOneByid } from '@/api/decorate'
import { otherFiltersItem } from '@/utils'
export default {
  name: 'Units',
  props: {
    selData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      columns: [
        {
          prop: 'unitName',
          label: '施工单位名称',
          minWidth: 150,
          className: 'btn-green',
          isButton: true,
          clickFun: this.toDetail
        },
        {
          prop: 'principal',
          label: '负责人',
          width: 120,
          hide: true
        },
        {
          prop: 'principalPhone',
          label: '负责人电话',
          width: 130,
          hide: true
        },
        {
          prop: 'signUpTime',
          label: '签约时间',
          width: 140,
          formatData: this.$parseTimeYMD('signUpTime'),
          searchType: 'date',
          hide: true
        },
        {
          prop: 'cooperationState',
          label: '合作状态',
          width: 100,
          propEnum: {
            domainCode: 'marketing',
            appCode: 'slm',
            dictTypeCode: 'COOPERATION_STATE'
          },
          hide: true
        },
        {
          prop: 'assessSumScore',
          label: '评估总分',
          width: 100,
          operator: '=',
          hide: true
        },
        {
          prop: 'currentWarrantyNumber',
          label: '保证金总金额',
          width: 100,
          operator: '=',
          hide: true
        },
        {
          prop: 'sameTimeMaxProject',
          label: '在建项目数量',
          width: 100,
          operator: '=',
          hide: true
        },
        {
          prop: 'sameTimeMaxArea',
          label: '在建项目总面积',
          width: 110,
          operator: '=',
          hide: true
        }
      ],
      selections: [],
      maxBatch: {},
      detail: {}
    }
  },
  computed: {
    // alertTitle() {
    //   return `当前委派批次${this.maxBatch}`
    // },
    filtersRaw() {
      // 2.施工单位默认显示范围：
      // 2.1当前办事处关联的，合作状态为“正常合作”的门店；
      // 2.2曾经与当前门店合作过，合作状态为“正常合作”的门店；
      // 2.3若系统默认显示的施工单位不满足条件，可通过施工单位名称手工筛选
      return [
        otherFiltersItem('cooperationState', 'B', '=')
      ]
    },
    paramsRaw() {
      if (this.selData.length > 0) {
        const t = this.selData[0]
        return { officeCode: t.officeCode, shopCode: t.shopCode }
      }
      return {}
    },
    selectonSetting() {
      const setting = [...this.tableConfig.setting]
      setting.unshift({
        label: '序号',
        render: (h, row) => {
          const removeHandle = () => {
            this.removeHandle(row)
          }
          return h('div', {
            style: {
              display: 'flex',
              alignItems: 'center'
            }
          }, [
            h('span', { style: { display: 'inline-block', paddingRight: '10px' }}, row.keyIndex + 1),
            h('svg-icon', { props: {
              iconClass: 'cuowuguanbiquxiao-solid_'
            }, style: { cursor: 'pointer' },
            nativeOn: {
              click: removeHandle
            }})
          ])
        }
      })
      return {
        interfacePath: '',
        setting
      }
    }
  },
  methods: {
    openFun() {
      if (this.selData.length === 0) {
        this.$message.warning('请选择数据！')
        return false
      }
      // 1.同一门店，不同装修任务号，可批量委派，若勾选数据中，包含不同门店，则弹框提示：一次只能对相同门店批量委派施工单位，请检查勾选数据；
      const decorationTaskCode = {}
      this.selData.forEach(e => {
        if (decorationTaskCode[e.decorationTaskCode] === undefined) {
          decorationTaskCode[e.decorationTaskCode] = 0
        }
        decorationTaskCode[e.decorationTaskCode] += 1
      })
      if (Object.entries(decorationTaskCode).some(e => e[1] > 1)) {
        this.$message.warning('存在相同装修任务号，请检查勾选数据')
        return false
      }
      const scs = this.selData.map(e => e.shopCode)
      if ((new Set(scs)).size !== 1) {
        this.$message.warning('一次只能对相同门店批量委派施工单位，请检查勾选数据')
        return false
      }
      return true
    },
    openHandle() {
      const d = this.selData.map(e => e.decorationTaskCode)
      getDetailBatch(d).then(res => {
        this.maxBatch = {}
        for (const item of res.data || []) {
          if (this.maxBatch[item.decorationTaskCode] === undefined) {
            this.maxBatch[item.decorationTaskCode] = item.delegateBatch
          } else if (this.maxBatch[item.decorationTaskCode] < item.delegateBatch) {
            this.maxBatch[item.decorationTaskCode] = item.delegateBatch
          }
        }
      })
      this.getDetail()
    },
    closedHandle() {
      this.detail = {}
    },
    getDetail() {
      getGetOneByid(this.selData[0].id).then(res => {
        this.detail = res.data
      })
    },
    selectionChange(v) {
      this.selections = v
    },
    handlerData() {
      const data = []
      for (const d of this.selData) {
        for (const item of this.selections) {
          const delegateBatch = this.maxBatch[d.decorationTaskCode]
          data.push({
            constCode: d.constCode, // 门店建设号
            constUnitCode: item.unitCode, // 委派施工单位编号
            decorationTaskCode: d.decorationTaskCode, // 装修任务编号
            unitName: item.unitName, // 委派施工单位名称
            delegateBatch: delegateBatch === undefined ? 1 : delegateBatch + 1
          })
        }
      }
      return data
    },
    confirmHandle() {
      if (this.selections.length === 0) {
        this.$message.warning('请选择施工单位！')
        return
      }
      return postBatchCreateUnit(this.handlerData()).then(res => {
        this.$message.success('操作成功！')
        this.$emit('on-success')
        this.$refs.cWithDialog.visible = false
      })
    },
    cancelHandle() {
      this.$refs.cWithDialog.visible = false
    },
    toDetail(row) {
      this.$store.dispatch('views/goPage', { path: '/constructionUnitMng/unitManagement', query: { target: 'detail', id: row.id, time: new Date().getTime() }})
    },
    removeHandle(row) {
      const i = this.selections.indexOf(row)
      if (i !== -1) {
        this.$refs.cTableBox.getTableBox().toggleRowSelection(row, false)
      }
    }
  }
}
</script>
